package com.hao.main;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.DateFormat.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
 
 
import com.google.android.gms.internal.bu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.provider.Settings;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import GPSHeilper.GPSTracker; 
import GiaoHangVietNam.Entities.GoodsInfor;
import GiaoHangVietNam.Entities.InterChangeInvoices;
import GiaoHangVietNam.Entities.InvoiceDetails;
import GiaoHangVietNam.RawInfor.ClientControlMessage;
import GiaoHangVietNam.RawInfor.EventCode;
import GiaoHangVietNam.RawInfor.GlobalStatus;
import GiaoHangVietNam.RawInfor.ServerMessageTypeID;
import GiaoHangVietNam.TCP.TCPClient;

public class MainActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	TextView headerInfor;
	// Chứa danh sách đơn hàng
	ListView listInvoicelv;

	// Handler chưa danh sách đơn hàng
	private ArrayList<InvoiceDetails> listInvoice = new ArrayList<InvoiceDetails>();
	private InvoiceArrayAdapter invoiceAdapter = null;
	private InvoiceDetails tmpInvoice;
	private int currentInvoiceIndex = 0;
	public static final int INVOICE_STATUS = 0;
	private TCPClient mTcpClient;
	private Boolean isWaitingInvoice = false; 
	public GpsListener gpsListener;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listInvoicelv = (ListView) findViewById(R.id.list_ship_to_day_lv);
		listInvoicelv.setOnItemClickListener(this);
		// Nhận dữ liệu các đơn hàng từ server
		listInvoice = getListInvoice();
		invoiceAdapter = new InvoiceArrayAdapter(this, R.layout.item_list_ship,
				listInvoice);
		listInvoicelv.setAdapter(invoiceAdapter);

		headerInfor = (TextView) findViewById(R.id.list_ship_to_day_tv);
		headerInfor.setText("Danh sách đơn hàng sắp tới");

		// enableWifi();
		enableInternet(true);  
		gpsListener = new GpsListener(this);  
		ClientControlMessage.Inits(1,(short)1, getIMEI());
		
		
		// connect to the server
		new connectTask().execute(""); 
		startTimer();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		gpsListener.requestUpdate();
	}

	private int countTime = 0;
	private int countTimeToPing = 0;
	// 30 giây gửi bản tin 1 lần
	private final long TIME_TO_SEND_CYCLE = 6;
	private final long TIME_TO_GET_PING = 2;
	private Boolean isConnected = false;
	private Boolean isConnecting = false;

	public void updateLocation(Location location)
	{
		ClientControlMessage.CurrentGeo =new LatLng(location.getLatitude(), location.getLongitude());
	}
	private void startTimer() {
		CountDownTimer counter = new CountDownTimer(Long.MAX_VALUE, 5000) {

			public void onTick(long millisUntilDone) {
				try { 
					countTime++;
					countTimeToPing++;
					isConnecting = isNetworkAvailable();
					// Nếu mới kết nối lại mạng
					if (isConnected == false && isConnecting == true) {
						new connectTask().execute("");
					} else {
						// Phải kết nối mới kết nối lại
						if (isConnecting == true) {
							// Kiểm tra xem đã nhận bản tin chưa
							if (countTimeToPing >= TIME_TO_GET_PING) {
								// Nếu sau 10 giây mà chưa nhận được bản tin
								// ping thì kết nối lại
								if (GlobalStatus.IsTCPConnecting == false) {
									new connectTask().execute("");
								} else {
									GlobalStatus.IsTCPConnecting = false;
								}
								countTimeToPing = 0;
							}
						}
					}
					if (countTimeToPing >= TIME_TO_GET_PING)
						countTimeToPing = 0;

					if (countTime == TIME_TO_SEND_CYCLE) {
						if (isConnecting == true) {   
							mTcpClient.sendMessage(ClientControlMessage
									.CycleGPS());
						}
						countTime = 0;
					}
					isConnected = isConnecting;
				} catch (Exception ex) {
				}
			}

			public void onFinish() {
			}
		}.start();
	}
	 
	private void enableWifi() {
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		// Nếu chưa bật thì bật wifi
		if (wifi.isWifiEnabled() == false)
			wifi.setWifiEnabled(true);
	}

	private void enableInternet(boolean yes) {
		ConnectivityManager iMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Method iMthd = null;
		try {
			iMthd = ConnectivityManager.class.getDeclaredMethod(
					"setMobileDataEnabled", boolean.class);
		} catch (Exception e) {
		}
		iMthd.setAccessible(false);
		if (yes) {
			try {
				iMthd.invoke(iMgr, true);
			} catch (IllegalArgumentException e) {

			} catch (IllegalAccessException e) {

				e.printStackTrace();
			} catch (Exception ex) {

			}
		} else {
			try {
				iMthd.invoke(iMgr, true);
			} catch (Exception e) {
			}
		}
	}

	private void enableGPSOn() {
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

		if (provider.contains("gps")) { // if gps is disabled
			final Intent poke = new Intent();
			poke.setClassName("com.android.settings",
					"com.android.settings.widget.SettingsAppWidgetProvider");
			poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			poke.setData(Uri.parse("3"));
			sendBroadcast(poke);
		}
	}

	// Sáng màn hình
	private void turnOnScreen() {
		Window window = this.getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

	}
 

	// Lấy số IMEI của thiết bịs
	private String getIMEI() {
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId();
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	// đang set dữ liệu giả để test
	private ArrayList<InvoiceDetails> getListInvoice() {
		ArrayList<InvoiceDetails> ret = new ArrayList<InvoiceDetails>();

		//String data = "1#19#Cty điện tử bình anh#Yến#01688514498#8 Thịnh liệt#20.9739837646484#105.841842651367#0#19;sách marketing;200;20";
//
		//String fields[] = data.split("#");
		//ret.add(new InvoiceDetails(fields));
		//
		// data="1#2#zonmob#Mr.Hải#01688514498#1141 Giải phóng#21.041408#105.767072#1#1;dien thoai;1000;20";
		//
		// fields = data.split("#");
		// ret.add(new InvoiceDetails(fields));
		return ret;
	}

  

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// Nếu đang chờ đơn hàng=> không nên cho chọn
		if (isWaitingInvoice == true) {
			Toast.makeText(getApplicationContext(), "Chưa có đơn hàng mới",
					Toast.LENGTH_LONG).show();
			return;
		}
		currentInvoiceIndex = position;
		// TODO Auto-generated method stub
		// tạo intent và bundle dữ liệu sang
		tmpInvoice = listInvoice.get(position);
		Intent intent = new Intent(this, DetailInvoiceActivity.class);
		intent.putExtra("MyPackage", tmpInvoice);
		intent.putExtra("index", currentInvoiceIndex);
		intent.putExtra("IsNewInvoice", false);

		// startActivity(intent);
		startActivityForResult(intent, INVOICE_STATUS);

		// String
		// data="@4#1#Huong#01688514498#247 tran dai nghia#21.041408#105.767072##giay;depdepdepdepdepdepdepdepdep;cap";
		// String[] field =data.split("#");
		// processInterChangeInvoice(field);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	// Phương thức này được gọi khi Activity con trả về kết quả
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null) {
			return;
		}
		// Nếu định danh lúc gửi là trạng thái đơn hàng
		if (requestCode == INVOICE_STATUS) { 

			// lấy giá trị kết quả
			Bundle bundle = data.getBundleExtra("MyPackage");
			int result = bundle.getInt("InvoiceStatus"); 
			switch (result) {

			case EventCode.FINISH_INVOICE: 
				isWaitingInvoice = true;
				if (tmpInvoice.IsSending == false) { 
					listInvoice.set(currentInvoiceIndex, tmpInvoice);
				} else {
					tmpInvoice.IsFinish = true;
					listInvoice.set(currentInvoiceIndex, tmpInvoice);
					int length = listInvoice.size();

					for (int i = 1; i < length; i++) {
						Collections.swap(listInvoice, i, i - 1);
					}
				}

				mTcpClient.sendMessage(ClientControlMessage
						.FinishInvoice());
				invoiceAdapter.notifyDataSetChanged();
				break;
			case EventCode.CANCEL_INVOICE:
				isWaitingInvoice = true;
				tmpInvoice.IsWaiting = true;
				listInvoice.set(currentInvoiceIndex, tmpInvoice);
				int length = listInvoice.size();

				for (int i = 1; i < length; i++) {
					Collections.swap(listInvoice, i, i - 1);
				}
				mTcpClient.sendMessage(ClientControlMessage
						.CancelInvoice());
				invoiceAdapter.notifyDataSetChanged();
				break;
			case EventCode.FINISH_INTERCHANGE:
				Log.e("FINISH_INTERCHANGE", "FINISH_INTERCHANGE");
				mTcpClient.sendMessage(ClientControlMessage
						.FinishInterChangeInvoice());
				break;
			case EventCode.CANCEL_INTERCHANGE:
				Log.e("FINISH_INTERCHANGE", "CANCEL_INTERCHANGE");
				mTcpClient.sendMessage(ClientControlMessage
						.CancelInterChangeInvoice());
				break;
			}
		}
	}

	public class connectTask extends AsyncTask<String, String, TCPClient> {

		@Override
		protected TCPClient doInBackground(String... message) {

			// we create a TCPClient object and
			mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
				@Override
				// here the messageReceived method is implemented
				public void messageReceived(String message) {
					// this method calls the onProgressUpdate
					publishProgress(message);
				}
			});
			mTcpClient.run();

			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			if (values.length > 0) {
				ProcessDataFromServer(values[0]);
			}

		}
	}

	private void ProcessDataFromServer(String data) {
		// Đánh dấu đã nhận bản tin

		GlobalStatus.IsTCPConnecting = true;

		if (data.startsWith("@") == true) {
			// Vibrate for 500 milliseconds

			String remainData = data.substring(1);
			String[] fields = remainData.split("#");

			if (fields.length > 0) {
				int id = Integer.parseInt(fields[0]);
				switch (id) {
				// Thông tin đơn hàng mới
				case ServerMessageTypeID.NEW_INVOICE:
					processNewInvoice(fields);
					break;
				// Nếu hủy đơn
				case ServerMessageTypeID.CANCEL_INVOICE:
					processCancelInvoice(fields);
					break;
				// Yêu cầu chuyển hàng
				case ServerMessageTypeID.INTERCHANGE_INVOICE:

					processInterChangeInvoice(fields);
					break;
				// Chỉ thêm đơn hàng trong nhóm đơn hàng
				case ServerMessageTypeID.ADD_INVOICE_TO_CURRENT:
					processAddInvoiceToCurrentInvoice(fields);
					break;
					
				case ServerMessageTypeID.FINISH_INTERCHANGE_SCREEN:
					finishActivity(INVOICE_STATUS);
					break;

				}
			}
		}
	}

	// Xử lý bản tin đơn hàng mới
	private void processNewInvoice(String[] fields) {

		isWaitingInvoice = false;
		currentInvoiceIndex = 0;

		tmpInvoice = new InvoiceDetails(fields);
		// Tìm xem đơn hàng đã tồn tai chưa
		int index = -1;

		for (int i = 0; i < listInvoice.size(); i++) {
			if (listInvoice.get(i).ID == tmpInvoice.ID) {
				index = i;
				break;
			}
		}
		if (index == 0)
			{
			
			 	if(listInvoice.get(0).IsSending == tmpInvoice.IsSending)
			 		return;
			 	else
			 		listInvoice.remove(0);
			} 
		if (index > 0)
			listInvoice.remove(index);
		
		listInvoice.add(0, tmpInvoice);

		invoiceAdapter.notifyDataSetChanged();
		Intent intent = new Intent(this, DetailInvoiceActivity.class);
		intent.putExtra("MyPackage", tmpInvoice);
		intent.putExtra("index", currentInvoiceIndex);
		intent.putExtra("IsNewInvoice", true);
		finishActivity(INVOICE_STATUS);
		// startActivity(intent);
		startActivityForResult(intent, INVOICE_STATUS);
	}

	// Xử lý bản tin hủy đơn hàng
	private void processCancelInvoice(String[] fields) {
		if (fields.length != 2)
			return;
		// Đánh dấu phải chờ đơn hàng
		if (isWaitingInvoice == false) {
			// Lấy id đơn hàng bị hủy
			int invoiceID = Integer.parseInt(fields[1]);
			// Lấy đơn hàng hiện tại
			tmpInvoice = listInvoice.get(0);
			// Hủy đơn hàng
			if (tmpInvoice.ListGoods.size() == 1) {
				finishActivity(INVOICE_STATUS);
				// TODO Auto-generated method stub
				alert("Đơn hàng bị hủy", "Chờ đơn hàng khác");
				tmpInvoice = listInvoice.get(0);
				tmpInvoice.IsWaiting = true;
				listInvoice.set(0, tmpInvoice);
				int length = listInvoice.size();

				for (int i = 1; i < length; i++) {
					Collections.swap(listInvoice, i, i - 1);
				}
				isWaitingInvoice = true;
			}
			// Chỉ hủy 1 đơn hàng trong 1 danh sách đơn hàng
			else {
				tmpInvoice = listInvoice.get(0);
				int removeIndex = -1;
				for (int i = 0; i < tmpInvoice.ListGoods.size(); i++) {
					if (tmpInvoice.ListGoods.get(i).ID == invoiceID) {
						removeIndex = i;
					}
				}
				if (removeIndex < 0)
					return;

				tmpInvoice.ListGoods.remove(removeIndex);
				listInvoice.remove(0);
				listInvoice.add(0, tmpInvoice);
				Intent intent = new Intent(this, DetailInvoiceActivity.class);
				intent.putExtra("MyPackage", tmpInvoice);
				intent.putExtra("index", currentInvoiceIndex);
				intent.putExtra("IsNewInvoice", false);
				finishActivity(INVOICE_STATUS);
				// startActivity(intent);
				startActivityForResult(intent, INVOICE_STATUS);
			}
			invoiceAdapter.notifyDataSetChanged();
		}
	}

	// Xử lý bản tin yêu cầu đổi hàng
	private void processInterChangeInvoice(String[] fields) {
		finishActivity(INVOICE_STATUS);
		// Lấy thông tin các đơn hàng
		InterChangeInvoices tmpInterChange = new InterChangeInvoices(fields);
		ClientControlMessage.UpdateInterChange(tmpInterChange.OtherShipperID,
				tmpInterChange.RegionID);
		Intent intent = new Intent(this, InterChangInvoiceDetailActivity.class);
		intent.putExtra("MyPackage", tmpInterChange);
		startActivityForResult(intent, INVOICE_STATUS);
	}

	// Xử lý bản tin cập nhật đơn hàng
	private void processAddInvoiceToCurrentInvoice(String[] fields) {
		tmpInvoice = listInvoice.get(0);
		tmpInvoice.AppendGoods(new GoodsInfor(fields, true));
		listInvoice.remove(0);
		listInvoice.add(0, tmpInvoice);

		invoiceAdapter.notifyDataSetChanged();
		Intent intent = new Intent(this, DetailInvoiceActivity.class);
		intent.putExtra("MyPackage", tmpInvoice);
		intent.putExtra("index", currentInvoiceIndex);
		intent.putExtra("IsNewInvoice", false);
		finishActivity(INVOICE_STATUS);
		// startActivity(intent);
		startActivityForResult(intent, INVOICE_STATUS);

	}

	private void alert(String tag, String content) {
		// TODO Auto-generated method stub
		android.app.AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(tag);
		alert.setMessage(content);
		alert.setPositiveButton("OK", null);
		alert.show();
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "Không được phép! ", Toast.LENGTH_SHORT).show();
	}
}
